<template>
  <div class="equipment">
    <div id="container"></div>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader';
import { getequipmentlist, getTitle } from '@/api/echarts';

let map = null;
let distCluster = null;
let pointSimplifierIns = null;

export default {
  name: 'index',
  data() {
    return {
      lat: null,
      lng: null,
      zoom: 5, // 设置一个默认值
    };
  },
  mounted() {
    this.initMap(); // 在组件挂载时初始化地图
  },
  methods: {
    async fetchlnglat() {
      try {
        const title = await getTitle();
        console.log(title, 'title');
        this.lat = parseFloat(title.msg.lat);
        this.lng = parseFloat(title.msg.lng);
        this.zoom = title.msg.zoom;

        // 检查经纬度是否有效
        if (!isNaN(this.lat) && !isNaN(this.lng) && map) {
          map.setCenter([this.lng, this.lat]); // 使用从接口返回的经纬度设置地图中心点
          map.setZoom(this.zoom);
        } else {
          console.error('无效的经纬度:', this.lat, this.lng, this.zoom);
        }
      } catch (error) {
        console.error('Error fetching title:', error);
      }
    },

    initMap() {
      AMapLoader.load({
        key: "f8c954755588cd09132500151dc4d01c",
        version: "2.0",
        plugins: ['AMap.Scale', 'AMap.Marker', 'AMap.InfoWindow', 'AMap.MarkerCluster'],
        AMapUI: {
          version: '1.1',
          plugins: ['overlay/SimpleMarker']
        }
      }).then((AMap) => {
        map = new AMap.Map("container", {
          viewMode: "2D",
          terrain: false,
          zoom: this.zoom, // 使用 data 中的 zoom 值
          center: [116.397428, 39.90923], // 使用默认中心点
          mapStyle: 'amap://styles/blue',
        });

        // 设置地图的边界，防止循环
        const bounds = new AMap.Bounds(
          new AMap.LngLat(73.502355, 3.837031),  // 西南角
          new AMap.LngLat(135.09567, 53.563624) // 东北角
        );
        map.setLimitBounds(bounds);

        this.aMapUiLoad(); // 确保地图 UI 组件加载
      }).catch(e => {
        console.log(`高德地图加载错误提示${e}`);
      });
    },

    initPage(DistrictCluster, PointSimplifier, utils) {
      function MyRender(distClusterIns, opts) {
        MyRender.__super__.constructor.apply(this, arguments);
      }

      utils.inherit(MyRender, DistrictCluster.Render.Default);

      utils.extend(MyRender.prototype, {
        drawMyLabel: function (feature, dataItems) {
  var pixelRatio = this.getPixelRatio();
  var containerPos = map.lngLatToContainer(feature.properties.centroid || feature.properties.center);
  var labelCtx = this._getCanvasCxt('mylabel');
  var centerX = containerPos.getX() * pixelRatio,
      centerY = containerPos.getY() * pixelRatio;

  var name = feature.properties.name;
  var count = ' (' + dataItems.length + ')';
  
  labelCtx.font = 14 * pixelRatio + 'px 微软雅黑';
  var nameMetrics = labelCtx.measureText(name);
  var countMetrics = labelCtx.measureText(count);
  var totalWidth = nameMetrics.width + countMetrics.width;

  var halfTxtWidth = totalWidth / 2;

  // 计算背景矩形的尺寸
  var rectWidth = totalWidth + 12 * pixelRatio; // 增加内边距
  var rectHeight = 22 * pixelRatio;
  var rectX = centerX - halfTxtWidth - 6 * pixelRatio;
  var rectY = centerY - rectHeight / 2;
  var cornerRadius = 5 * pixelRatio;

  // 绘制圆角矩形背景
  labelCtx.save();
  labelCtx.beginPath();
  labelCtx.moveTo(rectX + cornerRadius, rectY);
  labelCtx.lineTo(rectX + rectWidth - cornerRadius, rectY);
  labelCtx.quadraticCurveTo(rectX + rectWidth, rectY, rectX + rectWidth, rectY + cornerRadius);
  labelCtx.lineTo(rectX + rectWidth, rectY + rectHeight - cornerRadius);
  labelCtx.quadraticCurveTo(rectX + rectWidth, rectY + rectHeight, rectX + rectWidth - cornerRadius, rectY + rectHeight);
  labelCtx.lineTo(rectX + cornerRadius, rectY + rectHeight);
  labelCtx.quadraticCurveTo(rectX, rectY + rectHeight, rectX, rectY + rectHeight - cornerRadius);
  labelCtx.lineTo(rectX, rectY + cornerRadius);
  labelCtx.quadraticCurveTo(rectX, rectY, rectX + cornerRadius, rectY);
  labelCtx.closePath();

  // 设置背景颜色
  if (feature.properties.level === 'province') {
    labelCtx.fillStyle = '#ADD8E6'; // 浅蓝色背景
  } else if (feature.properties.level === 'district') {
    labelCtx.fillStyle = '#DDA0DD'; // 浅紫色背景
  } else {
    labelCtx.fillStyle = '#FFFFE0'; // 默认背景颜色
  }
  labelCtx.fill();

  // 绘制文本
  labelCtx.fillStyle = '#000000'; // 黑色文本
  labelCtx.textBaseline = 'middle';
  labelCtx.fillText(name, centerX - halfTxtWidth, centerY);

  // 绘制加粗的数字部分
  labelCtx.font = 'bold ' + 14 * pixelRatio + 'px 微软雅黑';
  labelCtx.fillText(count, centerX - halfTxtWidth + nameMetrics.width, centerY);

  labelCtx.restore();
}

        _initContainter: function () {
          MyRender.__super__._initContainter.apply(this, arguments);
          this._createCanvas('mylabel', this._container);
        },
        drawMyLabel: function (feature, dataItems) {
  var pixelRatio = this.getPixelRatio();
  var containerPos = map.lngLatToContainer(feature.properties.centroid || feature.properties.center);
  var labelCtx = this._getCanvasCxt('mylabel');
  var centerX = containerPos.getX() * pixelRatio,
      centerY = containerPos.getY() * pixelRatio;

  var text = feature.properties.name + ' (' + dataItems.length + ')';
  labelCtx.font = 'bold ' + 14 * pixelRatio + 'px 微软雅黑'; // 加入 'bold' 使字体加粗
  var textMetrics = labelCtx.measureText(text);
  var halfTxtWidth = textMetrics.width / 2;

  // 计算背景矩形的尺寸
  var rectWidth = textMetrics.width + 12 * pixelRatio; // 增加内边距
  var rectHeight = 22 * pixelRatio;
  var rectX = centerX - halfTxtWidth - 6 * pixelRatio;
  var rectY = centerY - rectHeight / 2;
  var cornerRadius = 5 * pixelRatio;

  // 绘制圆角矩形背景
  labelCtx.save();
  labelCtx.beginPath();
  labelCtx.moveTo(rectX + cornerRadius, rectY);
  labelCtx.lineTo(rectX + rectWidth - cornerRadius, rectY);
  labelCtx.quadraticCurveTo(rectX + rectWidth, rectY, rectX + rectWidth, rectY + cornerRadius);
  labelCtx.lineTo(rectX + rectWidth, rectY + rectHeight - cornerRadius);
  labelCtx.quadraticCurveTo(rectX + rectWidth, rectY + rectHeight, rectX + rectWidth - cornerRadius, rectY + rectHeight);
  labelCtx.lineTo(rectX + cornerRadius, rectY + rectHeight);
  labelCtx.quadraticCurveTo(rectX, rectY + rectHeight, rectX, rectY + rectHeight - cornerRadius);
  labelCtx.lineTo(rectX, rectY + cornerRadius);
  labelCtx.quadraticCurveTo(rectX, rectY, rectX + cornerRadius, rectY);
  labelCtx.closePath();

  // 设置背景颜色
  if (feature.properties.level === 'province') {
    labelCtx.fillStyle = '#ADD8E6'; // 浅蓝色背景
  } else if (feature.properties.level === 'district') {
    labelCtx.fillStyle = '#DDA0DD'; // 浅紫色背景
  } else {
    labelCtx.fillStyle = '#FFFFE0'; // 默认背景颜色
  }
  labelCtx.fill();

  // 绘制文本
  labelCtx.fillStyle = '#000000'; // 黑色文本
  labelCtx.textBaseline = 'middle';
  labelCtx.fillText(text, centerX - halfTxtWidth, centerY);

  labelCtx.restore();
}

      });

      pointSimplifierIns = new PointSimplifier({
        map: map,
        autoSetFitView: false,
        zIndex: 110,
        getPosition: function (item) {
          if (!item || !item.lnglat || isNaN(item.lnglat[0]) || isNaN(item.lnglat[1])) {
            return '';
          }
          return item.lnglat;
        },
        getHoverTitle: function (dataItem, idx) {
          return `<div style="height: 12vh;width: 16vw;background-color:#FFFFFF;margin:0;padding:0;z-index:9999999">
            <h2>第${idx+1}台设备</h2>
            <p>${dataItem.detail}</p>
          </div>`;
        },
        renderOptions: {
          pointStyle: {
            width: 6,
            height: 6,
            fillStyle: 'rgba(153, 0, 153, 0.38)'
          },
          hoverTitleStyle: {
            position: 'top'
          }
        }
      });

      distCluster = new DistrictCluster({
        zIndex: 100,
        map: map,
        autoSetFitView: false,
        getPosition: function (item) {
          if (!item || !item.lnglat || isNaN(item.lnglat[0]) || isNaN(item.lnglat[1])) {
            return null;
          }
          return item.lnglat;
        },
        renderConstructor: MyRender,
        renderOptions: {
          getClusterMarker: null,
          featureClickToShowSub: true,
          featureStyle: {
            fillStyle: 'rgba(192,192,192,0.5)',
            strokeStyle: 'rgba(0,0,0,0.5)',
            lineWidth: 1,
            hoverOptions: {
              fillStyle: 'rgba(255,255,255,0.01)',
              lineWidth: 2,
              strokeStyle: 'rgb(255,102,0)'
            }
          },
          getFeatureStyle: function (feature, dataItems) {
            if (feature.properties.name === '中国') {
              return {
                fillStyle: 'rgba(192,192,192,0.5)',
                strokeStyle: 'rgba(0,0,0,0.5)',
                lineWidth: 1,
              };
            } else {
              return {
                fillStyle: 'rgba(0, 115, 153, 0.6)',
                strokeStyle: 'rgba(0, 0, 0, 0.5)',
                lineWidth: 1,
              };
            }
          }
        }
      });

      window.distCluster = distCluster;

      getequipmentlist({ limit: 10000 }).then(res => {
        if (res.code === 0) {
          let data = res.msg;
          // console.log(data,'试试');
          
          let transformedData = data
            .filter(item => {
              return !isNaN(parseFloat(item.lng)) && !isNaN(parseFloat(item.lat));
            })
            .map(item => {
              return {
                lnglat: [parseFloat(item.lng), parseFloat(item.lat)],
                name: item.name,
                detail: item.detail, // 添加 detail 字段
                iSWorkorder: item.iSWorkorder,
                id: item.id,
                mainBind: item.mainBind,
                status: item.status,
                type: item.type,
                count: item.count
              };
            });

          distCluster.setData(transformedData);
          pointSimplifierIns.setData(transformedData);
        } else {
          console.error('API 返回错误:', res);
        }
      }).catch(error => {
        console.error('请求出错:', error);
      }).finally(() => {
        // loading.close();
      });
    },

    aMapUiLoad() {
      AMapUI.load(['ui/geo/DistrictCluster', 'ui/misc/PointSimplifier', 'lib/$', 'lib/utils'], (DistrictCluster, PointSimplifier, $, utils) => {
        this.initPage(DistrictCluster, PointSimplifier, utils);
        this.fetchlnglat(); // 确保地图 UI 组件加载完成后再调用 fetchlnglat
      });
    }
  }
};
</script>

<style lang="scss">
.equipment {
  #container {
    width: 100%;
    height: 120vh;
  }

  .amap-ui-district-cluster-region {
    background-color: rgba(192,192,192,0.5) !important; // 银白色背景
  }
}
</style>
